local tongdu = fk.CreateSkill {
  name = "ls__tongdu",
  anim_type = "support",
}

local lvshi = require "packages/lvshi/utility"

tongdu:addEffect(fk.TurnStart, {
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(tongdu.name)
  end, 
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- 获取所有己方角色
    local allies = table.filter(room:getAlivePlayers(), function(p)
      return lvshi.isFriend(player, p)
    end)
    if #allies == 0 then return end
    -- 所有己方角色依次交牌
    for _, ally in ipairs(allies) do
      if not ally.dead then
        local other_allies = table.filter(allies, function(p) return p ~= ally and not p.dead end)
        if #other_allies > 0 then
          local tos, cards = room:askToChooseCardsAndPlayers(ally, {
            min_num = 1,
            max_num = 1,
            min_card_num = 1,
            max_card_num = 1,
            targets = other_allies,
            skill_name = tongdu.name,
            prompt = "#ls__tongdu-give",
            cancelable = false,
          })
          if #tos > 0 and #cards > 0 then
            room:moveCardTo(cards, Card.PlayerHand, tos[1], fk.ReasonGive, tongdu.name, nil, false, ally)
          end
        end
      end
    end
    
    -- 检查手牌最多的己方角色
    local max_cards = 0
    for _, ally in ipairs(allies) do
      max_cards = math.max(max_cards, ally:getHandcardNum())
    end
    local max_allies = table.filter(allies, function(p) return p:getHandcardNum() == max_cards end)
    -- 如果没有任何己方角色有手牌，则不执行后续效果
    if #max_allies > 0 and max_cards > 0 then
      -- 检查技能发动者是否在最多手牌的角色中
      if table.contains(max_allies, player) then
        -- 如果技能发动者是手牌最多的角色之一，摸两张牌
        room:drawCards(player, 2, tongdu.name)
      else
        -- 否则所有手牌最多的角色依次视为使用【杀】
        for _, p in ipairs(max_allies) do
          if not p.dead then
            room:askToUseVirtualCard(p, {
              name = "slash",
              skill_name = tongdu.name,
              prompt = "#ls__tongdu-slash",
              cancelable = false,
            })
          end
        end
      end
    end
  end,
})

Fk:loadTranslationTable{
  ["ls__tongdu"] = "统度",
  [":ls__tongdu"] = "回合开始时，你可以令所有己方角色依次将一张牌交给另一名己方角色，然后若手牌最多的己方角色为你，你摸两张牌，否则其视为使用【杀】。",
  ["#ls__tongdu-give"] = "统度：选择一名己方角色并交给其一张牌",
  ["#ls__tongdu-slash"] = "统度：你须视为使用一张【杀】",
}

return tongdu